/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.advertising;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gcm.GCMBaseIntentService;

/**
 * IntentService responsible for handling GCM messages.
 */
public class GCMIntentService extends GCMBaseIntentService {
	private static final String TAG = "GCMIntentService";
	private GcmManager gcmManager;

	public GCMIntentService() {
		super(Constants.SENDER_ID);
	}

	@Override
	protected void onRegistered(Context context, String registrationId) {
		Log.i(TAG, "Device registered: regId = " + registrationId);
		sendRegIdtoServer(context, registrationId);
	}

	private void sendRegIdtoServer(Context context, String registrationId) {
		final SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(context);
		Editor editor = prefs.edit();
		// luu ngay nhan duoc REG_ID
		SimpleDateFormat spd = new SimpleDateFormat("yyMMdd");
		String today = spd.format(Calendar.getInstance().getTime());
		editor.putString(Constants.GCM_REG_ID, registrationId);
		editor.putString(Constants.GCM_REG_ID_DATE, today);
		editor.commit();
		// new SendRegIdAsync(context).execute(registrationId);
		postRegId(context, registrationId);
		// send to server
	}

	private void postRegId(Context mContext, final String regID) {
		TelephonyManager telephonyManager = (TelephonyManager) mContext
				.getSystemService(Context.TELEPHONY_SERVICE);
		final String imei = telephonyManager.getDeviceId();
		Log.i(TAG, "imei = " + imei);
		final String URL = Constants.REST_SERVER + Constants.REST_REGISTER;
		// Post params to be sent to the server
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("regID", regID);
		params.put("imei", imei);
		StringRequest postRequest = new StringRequest(Request.Method.POST, URL,
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						// response
						Log.d("Response", response);
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// error
						Log.d("Error.Response", error.toString());
					}
				}) {
			@Override
			protected Map<String, String> getParams() {
				Map<String, String> params = new HashMap<String, String>();
				params.put("regID", regID);
				params.put("imei", imei);
				return params;
			}
		};
		RequestQueue queue = Volley.newRequestQueue(mContext);
		queue.add(postRequest);
		// add the request object to the queue to be executed
		// ApplicationController.getInstance().addToRequestQueue(req);
	}

	@Override
	protected void onUnregistered(Context context, String registrationId) {
		Log.i(TAG, "Device unregistered");
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		gcmManager = GcmManager.getInstance(context);
		Bundle bundle = intent.getExtras();
		gcmManager.processMessage(bundle);
	}

	@Override
	protected void onDeletedMessages(Context context, int total) {
		Log.i(TAG, "Received deleted messages notification");
	}

	@Override
	public void onError(Context context, String errorId) {
		Log.i(TAG, "Received error: " + errorId);
	}

	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		// log message
		Log.i(TAG, "Received recoverable error: " + errorId);
		return super.onRecoverableError(context, errorId);
	}

}
